import { Message } from "element-ui";
import request from "@/utils/request";
// 复制函数
export const copyToClipboard = text => {
  let textArea = document.createElement("textarea");
  textArea.style.position = "fixed";
  textArea.style.top = "-100px";
  textArea.style.left = "-100px";
  textArea.value = text;
  document.body.appendChild(textArea);
  textArea.select();
  try {
    const successful = document.execCommand("copy");
    const msg = successful ? "已复制" : "该浏览器不支持点击复制到剪贴板";
    Message({
      message: msg,
      type: successful ? "success" : "warning"
    });
  } catch (err) {
    Message({
      message: "该浏览器不支持点击复制到剪贴板",
      type: "warning"
    });
  }
  document.body.removeChild(textArea);
};

//下载图片
export const fileDownload = (imgurl, filename = "file") => {
  // 创建隐藏的可下载链接
  const eleLink = document.createElement("a");
  eleLink.download = filename + `_${Math.round(new Date().getTime() / 1000)}`;
  eleLink.style.display = "none";
  // 图片转base64地址
  const img = document.createElement("img");
  img.setAttribute("crossOrigin", "anonymous");
  img.src = imgurl;
  img.onload = () => {
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    const scale = 1; //图片比例
    canvas.width = img.width * scale; // 画布宽度
    canvas.height = img.height * scale; // 画布高度
    ctx.imageSmoothingEnabled = true;
    ctx.drawImage(img, 0, 0, img.width * scale, img.height * scale);
    eleLink.href = canvas.toDataURL("image/jpeg", 1.0);
    document.body.appendChild(eleLink);
    eleLink.click();
    document.body.removeChild(eleLink);
  };
};
/**
 * 对象转url参数
 */
export function obj2urlParams(obj) {
  if (obj && typeof obj === "object") {
    let paramArr = [];
    Object.keys(obj).forEach(key => {
      let value = obj[key];
      let param = `${key}=${value}`;
      paramArr.push(param);
    });
    return paramArr.join("&");
  }
  return "";
}
// 地理位置code和name映射
let locationMap = null;
// 将地址数据深度遍历，构建locationMap
function getAllAddressNode(nodes) {
  if (!nodes || nodes.length === 0) {
    return;
  }
  nodes.forEach(item => {
    if (!locationMap) {
      locationMap = {
        "-1": "全国" // 设置全国 key-value
      };
    }
    if (!locationMap[item.code]) {
      locationMap[item.code] = item.name;
    }
    if (item.children && item.children.length > 0) {
      getAllAddressNode(item.children);
    }
  });
}
/**
 * 地理位置code和name映射
 */
export function getLocalMap() {
  if (locationMap) {
    return Promise.resolve(locationMap);
  }
  let localAddressStr = sessionStorage.getItem("addressData") || "[]";
  let localAddress = JSON.parse(localAddressStr) || [];

  if (!localAddress || localAddress.length === 0) {
    return getAllLocalData().then(list => {
      // 1.将数据本地化
      // 2.通过level解析数据
      sessionStorage.setItem("addressData", JSON.stringify(list));
      getAllAddressNode(list);
      return locationMap;
    });
  }
  getAllAddressNode(localAddress);
  return Promise.resolve(locationMap);
}
/**
 * 获取所有层级位置数据
 */
function getAllLocalData() {
  return request({
    url: "/api/commonApi/getAllArea",
    methods: "get"
  }).then(res => {
    let list = res.data || [];
    return list;
  });
}
/**
 * 获取对应层级的位置数据
 * @param {*} list 所有层级的数据
 * @param {*} level 层级数
 */
function rebuildAddressDataByLevel(list = [], level) {
  if (!list || list.length === 0) {
    return null;
  }
  let result = [];
  try {
    list.forEach(item => {
      // 初始化节点
      let obj = {
        label: item.name,
        value: item.code
      };
      // 递归地址
      if (typeof level === "undefined") {
        if (item.children && item.children.length > 0) {
          obj.children = rebuildAddressDataByLevel(item.children);
        }
      } else if (level > 1) {
        obj.children = rebuildAddressDataByLevel(item.children, level - 1);
      }
      result.push(obj);
    });
    return result;
  } catch (e) {
    return null;
  }
}
// 获取地址数据
export function getAddressDataByLevel(level) {
  let localAddressStr = sessionStorage.getItem("addressData") || "[]";
  let localAddress = JSON.parse(localAddressStr) || [];

  if (!localAddress || localAddress.length === 0) {
    return getAllLocalData().then(list => {
      // 1.将数据本地化
      // 2.通过level解析数据
      sessionStorage.setItem("addressData", JSON.stringify(list));
      return rebuildAddressDataByLevel(list, level);
    });
  }
  return Promise.resolve(rebuildAddressDataByLevel(localAddress, level));
}
/**
 * 格式化时间
 * @params {number} 时间戳
 * @params {string} 格式
 * @return {string} 格式化时间
 */

export function formatTime(time,fmtstr){
  const date = new Date(time);
  let ret;
  const opt = {
    "Y+": date.getFullYear().toString(),        // 年
    "m+": (date.getMonth() + 1).toString(),     // 月
    "d+": date.getDate().toString(),            // 日
    "H+": date.getHours().toString(),           // 时
    "M+": date.getMinutes().toString(),         // 分
    "S+": date.getSeconds().toString()          // 秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmtstr);
      if (ret) {
          fmtstr = fmtstr.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
      }
  }
  return fmtstr;
}


export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}
